from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Course,Student
from .serializer import CourseSerializer,StudentSerializer

class CourseList(APIView):
    def get(self, request,id):
        try:
            courses = Course.objects.get(id=id)
            serializer = CourseSerializer(courses)
            return Response(serializer.data,status=status.HTTP_200_OK)
        except Course.DoesNotExist:
            return Response({'error':'不存在'},status=status.HTTP_400_BAD_REQUEST)

class StudentList(APIView):
    def get(self, request,id):
        try:
            student = Student.objects.get(id=id)
            serializer = StudentSerializer(student)
            return Response(serializer.data,status=status.HTTP_200_OK)
        except Student.DoesNotExist:
            return Response({'error':'不存在'},status=status.HTTP_400_BAD_REQUEST)

class StudentAdd(APIView):
    def post(self,request):
        name = request.data.get('name')
        sex = request.data.get('sex')
        age = request.data.get('age')

        if not all([name,sex,age]):
            return Response({'error':'不能输入为空'},status=status.HTTP_400_BAD_REQUEST)

        if Student.objects.filter(name=name).exists():
            return Response({'error':'不能重复'},status=status.HTTP_400_BAD_REQUEST)

        serializer=StudentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'succeed':'添加成功'},status=status.HTTP_200_OK)

# class CourseAdd(APIView):
#     def post(self,request):
#         hobby = request.data.get('hobby')
#         student_id = request.data.get('student_id')
#
#         print('----------------')
#         print(student_id)
#         print('----------------')
#
#         serializer = CourseSerializer(data=request.data)
#
#         try:
#             course = Course.objects.create(student_id=student_id,hobby=hobby)
#             course.save()
#             return Response({'succeed': '添加成功'}, status=status.HTTP_200_OK)
#         except Exception as e:
#             print(e)

class CourseAdd(APIView):
    def post(self,request):
        hobby = request.data.get('hobby')
        student_id = request.data.get('student_id')

        if not all([hobby,student_id]):
            return Response({'error':'不能输入为空'},status=status.HTTP_400_BAD_REQUEST)

        try:
            if Student.objects.filter(id=student_id).exists():
                    course = Course.objects.create(student_id=student_id,hobby=hobby)
                    course.save()
                    return Response({'succeed': '添加成功'}, status=status.HTTP_200_OK)
        except Exception:
            return Response({'error': '不存在'}, status=status.HTTP_400_BAD_REQUEST)

        # else:
        #     return Response({'error':'不存在'},status=status.HTTP_400_BAD_REQUEST)

